//
//  SpeechAudioController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/10.
//

import UIKit
import Reusable
import SnapKit

extension SpeechAudioController: NibLoadable {}

class SpeechAudioController: BaseTableViewController {
    
    @IBOutlet weak var zhView: UIView!
    @IBOutlet weak var ruView: UIView!
    
    @IBOutlet weak var zhTitleLabel: UILabel!
    @IBOutlet weak var ruTitleLabel: UILabel!
    
    var from: LanguageTpye = .zh
    
    private lazy var waveformView: WaveformView = {
        let view = WaveformView()
        view.backgroundColor = .clear
        view.isHidden = true
        return view
    }()
    
    /// 语音识别播放器
    private var synthesizer: AVSpeechSynthesizer?
    private var language: LanguageTpye = .zh
    private var list: [TranslationAudioModel] = []//TranslationAudioModel.loadSavedAccounts()
    
    
    let recorder = AudioRecorderManager()
    let speechManager = SpeechManager.shared
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        setupUI()
        setupSynthesizer()
        recorder.delegate = self
        
        zhView.tag = 0
        ruView.tag = 1
        zhView.sg.addLongGesture(self, #selector(handleLongPress))
        ruView.sg.addLongGesture(self, #selector(handleLongPress))
        zhView.sg.addTapGesture(self, #selector(handleTapPress))
        ruView.sg.addTapGesture(self, #selector(handleTapPress))
        
        speechManager.delegate = self
        speechManager.requestAuthorization { isAgree in
            if !isAgree {
                // 用户不同意,跳转到设置
            }
        }
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        stopAllResources()
    }
    
    /// 更新语言
    override func updateLanguageAction() {
        navigationItem.title = "语音翻译".localized(.tran)
//        zhTitleLabel.text = "说中文".localized(.tran)
//        ruTitleLabel.text = "На русском".localized(.tran)
    }
    
    deinit {
        stopAllResources()
    }
    
    private func stopAllResources() {
        stopSpeaking()
    }
    
}

// MARK: - private
private extension SpeechAudioController {
    
    func setupNav() {
        vhl_navBarBackgroundAlpha = 0
        updateLanguageAction()
    }
    
    func setupUI() {
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.rowHeight = 36
        tableView.register(cellType: TranslationAudioZHCell.self)
        tableView.register(cellType: TranslationAudioRUCell.self)
        tableView.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(xIphoneNavStatusBarHeight)
            make.bottom.equalTo(-(xIphoneBottomSafeHeight + 98 + 10))
        }
        scrollToBottom()
        
        view.addSubview(waveformView)
        waveformView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: 200, height: 100))
        }
        
    }
    
    func addItem(type: LanguageTpye, text: String, translation: String) {
        list.append(TranslationAudioModel(type: type == .zh ? 0: 1, text: text, translation: translation))
        tableView.reloadData()
        
        TranslationAudioModel.saveAccounts(list)
    }
    
    /// 滚动到最下
    func scrollToBottom() {
        
        UIView.animate(withDuration: 0, delay: 1.0, options: .allowUserInteraction, animations: {}) { finished in
            
            if self.tableView.isTracking ||
                self.tableView.isDragging ||
                self.tableView.isDecelerating {
                return
            }
            
            let index = self.list.count - 1
            if index >= 0 {
                self.tableView.scrollToRow(at: IndexPath(row: index, section: 0), at: .bottom, animated: true)
            }
        }
    }
    
    /// 翻译
    func translation(_ text: String) {
        if text.isEmpty {
            return
        }
        
        // 翻译
        let from = language == .zh ? "zh": "ru"
        let to = language == .zh ? "ru": "zh"
        YLHUD.showLottie()
        NeoNuiTranslation.translation(from: from, to: to, text: text) { [weak self] sourceText, result in
            guard let self = self else { return }
            DispatchQueue.main.async {
                if let dst = result {
                    YLHUD.hideHUD()
                    // 翻译结果 反显
                    self.addItem(type: self.language, text: text, translation: dst)
                    self.scrollToBottom()
                    
                } else {
                    YLHUD.showMessage("翻译失败")
                }
            }
        }
    }
}

// MARK: - Action
private extension SpeechAudioController {
    
    @objc func handleTapPress(_ tap: UITapGestureRecognizer) {
        guard let tag = tap.view?.tag else {
            return
        }
        
        let urlPath = "/var/mobile/Containers/Data/Application/01EDD685-9BA0-48AC-A2B4-03490CDFD2F2/Documents/my_recording_1747030129.m4a"
        let uRL = URL(string: urlPath)!
        let path = uRL.path
        xLog("url path \(path))")
        
        
        
        if tag == 1 {
            //
            //            do {
            //                try recorder.playRecording(at: uRL)
            //            } catch {
            //                xLog("播放录音失败: \(error)")
            //            }
            
            playLastRecording()
            
            return
        }
        
        if let lastRecording = recorder.allRecordings.last {
            xLog("播放: \(lastRecording.path)")
            // SpeechManager.shareInstance().createSpeech("zh_CN", url: lastRecording.path)
            
            speechManager.recognizeFromAudioFile(fileURL: lastRecording, language: .zh)
            
            
        }
        
        
        
        
        
        //        // 用来测试
        //        let text = """
        //            悯农
        //            唐 李绅
        //            锄 禾 日 当 午，
        //            汗 滴 禾 下 土。
        //            谁 知 盘 中 餐，
        //            粒 粒 皆 辛 苦 。
        //            """
        //
        //        let res = """
        //            вернон
        //            Тан ли джентри.
        //            День мотыги в полдень,
        //            Капли пота, капли грязи.
        //            Кто знает, что на тарелке,
        //            Все песчинки были горькими.
        //            """
        //        let type = arc4random()%2
        //        if type == 0 {
        //            language = .zh
        //            addItem(type: language, text: text, translation: res)
        //        } else {
        //            language = .ru
        //            addItem(type: language, text: res, translation: text)
        //        }
        //        scrollToBottom()
    }
    
    @objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
        guard let tag = gestureRecognizer.view?.tag else {
            return
        }
        
        if gestureRecognizer.state == .began {
            xLog("开始长按")
            self.waveformView.updateAmplitude(-159)
            waveformView.isHidden = false
            language = tag == 0 ? .zh: .ru
            startRecording()
            
        } else if gestureRecognizer.state == .ended {
            xLog("结束手势")
            stopRecording()
            waveformView.isHidden = true
        }
    }
    
}

// MARK: - UITableViewDelegate, UITableViewDataSource
extension SpeechAudioController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = list[indexPath.row]
        if model.type == 0 {
            let cell = tableView.dequeueReusableCell(for: indexPath, cellType: TranslationAudioZHCell.self)
            cell.model = model
            cell.delegate = self
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(for: indexPath, cellType: TranslationAudioRUCell.self)
        cell.model = model
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = list[indexPath.row]
        return model.cellHeight
    }
    
}

// MARK: - TranslationAudioCellDelegate
extension SpeechAudioController: TranslationAudioCellDelegate {
    func playContent(model: TranslationAudioModel) {
        speakTextWithDelay(text: model.translation, type: model.type == 0 ? .zh: .ru)
    }
}

// MARK: - 语音识别器
extension SpeechAudioController {
    func setupSynthesizer() {
        guard synthesizer == nil else { return }
        synthesizer = AVSpeechSynthesizer()
        synthesizer?.delegate = self
    }
    
    func stopSpeaking() {
        synthesizer?.stopSpeaking(at: .immediate)
        synthesizer = nil
    }
    
    /// 朗读文本
    func speakTextWithDelay(text: String, type: LanguageTpye) {
        
        setupSynthesizer()
        
        if synthesizer!.isSpeaking {
            YLHUD.showMessage("正在朗读中".localized(.tran))
            return
        }
        let utterance = AVSpeechUtterance(string: text)
        // 设置语言，例如使用英语（美国）en-US, 中文 zh-Hans
        let language = type == .zh ? "ru-RU": "zh-CN"
        utterance.voice = AVSpeechSynthesisVoice(language: language) // "zh-Hant-HK" 设置粤语
        // 设置语速 默认:0.5
        utterance.rate = AVSpeechUtteranceDefaultSpeechRate
        // 设置音调
        utterance.pitchMultiplier = 1.0
        // 设置音量
        utterance.volume = 1.0
        synthesizer?.speak(utterance)
        
        //        let averageCharDuration: TimeInterval = 0.5 // 每个字符的平均朗读时间，单位为秒
        //        // 调整基于语速的朗读时间
        //        let totalDuration = TimeInterval(text.count) * averageCharDuration / Double(utterance.rate)
        //        // 播放文本并停顿2秒后停止
        //        DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) { [weak self] in
        //            xLog("停止")
        //            self?.synthesizer.stopSpeaking(at: .word)
        //        }
    }
    
}

// MARK: - AVSpeechSynthesizerDelegate
extension SpeechAudioController: AVSpeechSynthesizerDelegate {
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        xLog("didFinish 播放完")
        xLog("\(synthesizer.isSpeaking ? "正在播放": "结束")")
        if synthesizer.isSpeaking {
            let res = synthesizer.stopSpeaking(at: .immediate)
            xLog("停止 : \(res ? "ok": "no")")
        }
        
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        xLog("didStart \(utterance)")
    }
    
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
        xLog("didCancel \(utterance)")
    }
}


// MARK: - 音频采集
extension SpeechAudioController {
    
    // MARK: - Button Actions
    
    func startRecording() {
        do {
            try recorder.startRecording(fileName: "meeting", fileExtension: "m4a")
        } catch {
            xLog("开始录音失败: \(error)")
        }
    }
    
    func pauseRecording() {
        do {
            try recorder.pauseRecording()
        } catch {
            xLog("暂停录音失败: \(error)")
        }
    }
    
    func resumeRecording() {
        do {
            try recorder.resumeRecording()
        } catch {
            xLog("继续录音失败: \(error)")
        }
    }
    
    func stopRecording() {
        do {
            try recorder.stopRecording()
        } catch {
            xLog("停止录音失败: \(error)")
        }
    }
    
    func playLastRecording() {
        if let lastRecording = recorder.allRecordings.last {
            do {
                xLog("播放: \(lastRecording.path)")
                try recorder.playRecording(at: lastRecording)
            } catch {
                xLog("播放录音失败: \(error)")
            }
        }
    }
    
}

extension SpeechAudioController: AudioRecorderManagerDelegate {
    func inputGainDidChange(_ gain: Float) {
        xLog("gain :\(gain)")
    }
    
    
    func recorderDidStart() {
        xLog("录音已开始")
    }
    
    func recorderDidPause() {
        xLog("录音已暂停")
    }
    
    func recorderDidResume() {
        xLog("录音已继续")
    }
    
    func recorderDidFinish(_ success: Bool, fileURL: URL?) {
        if success, let url = fileURL {
            xLog("录音完成，文件保存到: \(url)")
            // file:///var/mobile/Containers/Data/Application/01EDD685-9BA0-48AC-A2B4-03490CDFD2F2/Documents/my_recording_1747030129.m4a
            // SpeechManager.shareInstance().createSpeech("zh_CN", url: url.path)
            SpeechManager.shared.recognizeFromAudioFile(fileURL: url, language: .zh)
            
        } else {
            xLog("录音完成但失败")
        }
    }
    
    func recorderDidFail(with error: Error) {
        xLog("录音出错: \(error.localizedDescription)")
    }
    
    func recorderDidUpdateMeter(_ averagePower: Float, peakPower: Float) {
        // 可以在这里更新UI显示音量
        xLog("Average: \(averagePower), Peak: \(peakPower)")
        self.waveformView.updateAmplitude(Double(averagePower))
    }
    
    
}

extension SpeechAudioController: SpeechManagerDelegate {
    func didFinishRecognition(text: String, isSuccess: Bool, error: SpeechError?) {
        if isSuccess {
            xLog("转写结果 : \(text)")
            // 翻译
            let from = self.from == .zh ? "zh": "ru"
            let to = self.from == .zh ? "ru": "zh"
//            YLHUD.showLottie()
            NeoNuiTranslation.translation(from: from, to: to, text: text) { sourceText, result in
//                DispatchQueue.main.async {
//                    YLHUD.hideHUD()
                    if let dst = result {
                        // 翻译结果 反显
                        xLog("原文: \(sourceText ?? "nil")")
                        xLog("译文: \(dst)")
                        
                    } else {
                        YLHUD.showMessage("翻译失败")
                    }
//                }
            }
            
            
            
            
        } else {
            xLog("转写失败 : \(error?.errorDescription ?? "")")
        }
    }
    
    func didReceiveTranscription(text: String) {
        xLog("实时转写 : \(text)")
    }
    
    
    func didDetectUnsupportedLanguage(_ language: SpeechRecognitionLanguage) {
        xLog("不支持的语言 \(language.identifier)")
    }
    
    
}
